const healthApiModule = require('./utils/api/health');
const api = require('./utils/api');

App({
  // 全局变量
  globalData: {
    userInfo: null,
    token: null,
    isLoggedIn: false,
    healthData: null,
    theme: 'light', // 主题设置: light 或 dark
    statusBarHeight: 0,
    navBarHeight: 44,
    safeAreaBottom: 0,
    launchScene: 0,
    deviceConnected: false,
    deviceData: null,
    useRealApi: true,
    envType: 'prod',
    envVersion: ''
  },
  
  onLaunch: function () {
    console.log('应用启动: App Launch');
    
    // 初始化健康API模块的数据
    try {
      healthApiModule.initializeData();
      console.log('健康API模块数据初始化成功');
    } catch (error) {
      console.error('健康API模块数据初始化失败:', error);
    }
    
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    this.globalData.statusBarHeight = systemInfo.statusBarHeight;
    this.globalData.navBarHeight = 44; // 默认导航栏高度

    // 检查是否有更新版本
    this.checkUpdate();

    // 处理底部安全区域
    this.globalData.safeAreaBottom = systemInfo.screenHeight - systemInfo.safeArea.bottom;
    
    // 获取环境信息
    const accountInfo = wx.getAccountInfoSync();
    const envVersion = accountInfo.miniProgram.envVersion;
    this.globalData.envVersion = envVersion;
    
    // 环境类型设置
    if (envVersion === 'develop') {
      this.globalData.envType = 'dev';
    } else if (envVersion === 'trial') {
      this.globalData.envType = 'test';
    } else {
      this.globalData.envType = 'prod';
    }
    
    console.log(`当前环境: ${this.globalData.envType} (${envVersion})`);
    
    // 检查API模式设置
    const savedApiMode = wx.getStorageSync('useRealApi');
    if (savedApiMode !== undefined) {
      // 使用存储的设置
      this.globalData.useRealApi = savedApiMode;
    } else {
      // 默认使用真实API
      this.globalData.useRealApi = true;
      wx.setStorageSync('useRealApi', true);
    }
    
    // 为API工具设置模式
    api.health.setApiMode(this.globalData.useRealApi);
    
    // 显示当前API模式
    console.log('API模式:', this.globalData.useRealApi ? '真实API' : '模拟数据');
    
    // 自动登录
    this.autoLogin();
  },
  
  autoLogin: function() {
    const token = wx.getStorageSync('authToken');
    
    if (token) {
      this.globalData.token = token;
      this.globalData.isLoggedIn = true;
      
      // 获取用户信息
      if (!this.globalData.userInfo) {
        this.getUserInfo();
      }
    } else {
      // 如果不是登录页，跳转到登录页
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        if (currentPage.route !== 'pages/login/login') {
          wx.redirectTo({
            url: '/pages/login/login'
          });
        }
      }
    }
  },
  
  getUserInfo: async function() {
    // 尝试获取用户信息
    try {
      const { getUserProfile } = require('./utils/request');
      const result = await getUserProfile();
      
      if (result.success) {
        this.globalData.userInfo = result.data;
        return result.data;
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果token无效，清除登录状态
      if (error.message && error.message.includes('未授权')) {
        this.clearLoginState();
      }
    }
    
    return null;
  },
  
  // 清除登录状态
  clearLoginState: function() {
    this.globalData.token = null;
    this.globalData.userInfo = null;
    this.globalData.isLoggedIn = false;
    wx.removeStorageSync('token');
    
    // 跳转到登录页
    wx.redirectTo({
      url: '/pages/login/login'
    });
  },
  
  // 设置主题
  setTheme: function (theme) {
    this.globalData.theme = theme;
    wx.setStorageSync('theme', theme);
  },
  
  // 获取当前主题
  getTheme: function () {
    return this.globalData.theme;
  },

  // 当小程序启动，或从后台进入前台显示，会触发 onShow
  onShow: function(options) {
    // 更新自定义tabBar
    this.updateTabBar();

    // 记录启动场景
    this.globalData.launchScene = options.scene;
  },

  // 更新tabBar选中状态
  updateTabBar: function() {
    const pages = getCurrentPages();
    if (pages.length) {
      const currentPage = pages[pages.length - 1];
      if (typeof currentPage.getTabBar === 'function' && currentPage.getTabBar()) {
        currentPage.getTabBar().setData({
          selected: this.getTabBarIndex(currentPage.route)
        });
      }
    }
  },

  // 获取当前页面对应的tabBar索引
  getTabBarIndex: function(route) {
    const tabBarPages = [
      'pages/health/health',
      'pages/diet/diet',
      'pages/exercise/exercise',
      'pages/profile/profile'
    ];
    return tabBarPages.indexOf(route);
  },

  // 检查小程序更新
  checkUpdate: function() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function(res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本已准备好，是否重启应用？',
              success: function(res) {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              }
            });
          });
          
          updateManager.onUpdateFailed(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本下载失败，请检查网络后重试'
            });
          });
        }
      });
    }
  },
  
  // 切换API模式（仅开发环境可用）
  toggleApiMode: function() {
    const accountInfo = wx.getAccountInfoSync();
    const env = accountInfo.miniProgram.envVersion;
    
    // 非开发环境不允许切换
    if (env !== 'develop') {
      wx.showModal({
        title: '提示',
        content: '只有在开发环境下才能切换API模式',
        showCancel: false
      });
      return false;
    }
    
    // 获取当前模式并切换
    const currentMode = this.globalData.useRealApi;
    const newMode = !currentMode;
    
    // 更新存储和全局变量
    this.globalData.useRealApi = newMode;
    wx.setStorageSync('devApiMode', newMode ? 'real' : 'mock');
    wx.setStorageSync('useRealApi', newMode);
    
    // 更新API工具类设置
    api.health.setApiMode(newMode);
    
    console.log('[App] API模式已切换为:', newMode ? '真实API' : '模拟数据');
    
    // 返回新模式，便于调用者处理
    return newMode;
  }
})